import Vue from 'vue'
import Router from 'vue-router'
import qs from 'qs'
import {
  detecteDevice
} from '../common/systeminfo'

// Routes Components
import systemRoute from './modules/system'
import tabbarRoute from './modules/tabbar'
import authorizeRoute from './modules/authorize'
import appRoute from './modules/app'
import activityRoute from './modules/activity'
import feedbackRoute from './modules/feedback'
import passportRoute from './modules/passport'
import shopRoute from './modules/shop'
import userRoute from './modules/user'
import memberRoute from './modules/member'
import pageRoute from './modules/page'
// import testRoute from './modules/test'
// import JSBridge from '../common/JSBridge'
Vue.use(Router)
// const jsBridge = JSBridge.getInstance()

let routes = new Set([
  ...[{
    path: '/',
    redirect: '/home'
  }],
  ...tabbarRoute,
  ...authorizeRoute,
  ...appRoute,
  ...activityRoute,
  ...feedbackRoute,
  ...passportRoute,
  ...shopRoute,
  ...userRoute,
  ...memberRoute,
  ...pageRoute,
  ...systemRoute,
  // ...testRoute,
  ...[
    // 404 page must be placed at the end !!!
    {
      path: '*',
      redirect: '/exception'
    }
  ]
])

// add route path
routes.forEach(route => {
  route.path = route.path || '/' + (route.name || '')
})

const router = new Router({
  // mode: 'history',
  // base: process.env.assetsRoot,
  routes: routes,
  scrollBehavior (to, from, savedPosition) {
    return {
      x: 0,
      y: 0
    }
  }
})

router.beforeEach((to, from, next) => {
  console.log('router.beforeEach', to)
  let isWechatBrowser = detecteDevice('wechat')
  if (isWechatBrowser && to.path !== '/authorize/wechat') {
    let wxUserInfo = sessionStorage.getItem('wxUserInfo')
    if (!wxUserInfo) {
      // 保存当前路由地址，授权后还会跳到此地址
      sessionStorage.setItem('wxRedirectUrl', to.fullPath)

      // // 请求微信授权,并跳转到 /WxAuth 路由
      let params = qs.stringify({
        appid: process.env.WECHAT_APP_ID,
        redirect_uri: window.location.origin + '/#/authorize/wechat',
        response_type: 'code',
        scope: 'snsapi_userinfo',
        state: 'STATE'
      })

      // let appId = 'wx1b4b2f622534cd9e'
      // let redirectUrl = encodeURIComponent(window.location.origin + '/#/wechat/auth')
      // let wechatAuthUrl2 = `${process.env.WECHAT_OAUTH_URL}?appid=${appId}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`

      window.location.href = `${process.env.WECHAT_OAUTH_URL}?${params}#wechat_redirect`
      // next()
      return false
    } else {
      if (to.meta && to.meta.title) {
        document.title = to.meta.title
      }
      next()
    }
  } else {
    if (to.meta && to.meta.title) {
      document.title = to.meta.title
    }
    next()
  }
})

export default router
